import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import { useRouter } from "vue-router";

const router = useRouter();
const userStore = useUserStore();

const httpInstance = axios.create({
	baseURL: "https://pcapi-xiaotuxian-front-devtest.itheima.net",
	timeout: 50000
});

httpInstance.interceptors.request.use(
	config => {
		if (userStore.userInfo && (userStore.userInfo as { token: string }).token) {
			const token = userStore.userInfo.token;
			config.headers.Authorization = `Bearer ${token}`;
		}
		return config;
	},
	e => Promise.reject(e)
);

httpInstance.interceptors.response.use(
	res => res.data,
	e => {

		ElMessage({
			type: "warning",
			message: e.response?.data?.message,
		});

		if (e.response?.status === 401) {
			console.log("status = 401");
			userStore.clearUserInfo();
			router.push("/login");
		}

		return Promise.reject(e);
	}
);

export default httpInstance;